import { ReactElement, useState, useEffect } from 'react'
import style from './index.module.less'
import { Button, Space, message, Modal } from 'antd'
import { DownloadOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import unPic from '@imgs/xlsx-un.png'
import onPic from '@imgs/xlsx-on.png'
import { inputExcelRequest } from './ajax'
import { awaitWrap } from '@js/tool'
import { History } from 'history'
import HistoryModal from './components/historyModal'
import { Dispatch } from 'redux'
import { addWindow } from '@src/redux/actions/tab'
import { useDispatch } from 'react-redux'

const { confirm } = Modal

function changeFile (list: FileList | null, setFile: (v: File | null) => void): void {
  if (list === null || list.length === 0) {
    setFile(null)
    return undefined
  }
  const file = list[0]
  if (!/(\.xls|\.xlsx)$/.test(file.name)) {
    message.warning('文件格式必须为：XLSX').then(null, null)
    return undefined
  }
  setFile(file)
}

function confirmImport (file: File | null, setFile: (v: File | null) => void, dispatch: Dispatch): void {
  if (file === null) {
    return undefined
  }
  confirm({
    icon: <ExclamationCircleOutlined />,
    content: '确认是否导入案件？',
    onOk: () => {
      uploadHandle(file, setFile, dispatch).catch(e => console.error(e))
    }
  })
}

async function uploadHandle (file: File, setFile: (v: File | null) => void, dispatch: Dispatch): Promise<void> {
  const hide = message.loading('导入中')
  const [e, d] = await awaitWrap(inputExcelRequest(file))
  hide()
  if (e === null) {
    if (typeof d === 'string') {
      dispatch(addWindow({ id: `case--input-batch-case-list-${d}`, title: '批量导入案件', componentName: 'CaseInputBatchCaseList', forceRefresh: false, meta: { id: d } }))
    } else {
      setFile(null)
    }
  }
}

function Main (): ReactElement {
  const dispatch = useDispatch()
  const [file, setFile] = useState<File | null>(null)
  const [visible, setVisible] = useState(false)
  useEffect(() => {
    const r = document.querySelector('#uploadBlock')
    if (r !== null) {
      r.addEventListener('dragover', function (e): void {
        e.stopPropagation()
        e.preventDefault()
      })
      r.addEventListener('drop', function (e): void {
        e.stopPropagation()
        e.preventDefault()
        const data: DataTransfer | null = (e as DragEvent).dataTransfer
        if (data !== null) {
          changeFile(data.files, setFile)
        }
      })
    }
  }, [])
  return (
    <div className={style.container}>
      <HistoryModal visible={visible} hide={() => setVisible(false)} />
      <div className={style.body}>
        <div className={style.inner}>
          <div className={style['title-block']}>
            <div className={style['title-line']}><span className={style['title-text']}>1. 下载导入模板</span></div>
            <div className={style['subtitle-line']}>根据提示信息完善表格内容</div>
          </div>
          <div className={style['download-line']}>
            <Button icon={<DownloadOutlined />} block onClick={() => window.open('/upload/caseimport_templet_v1.xlsx')}>下载空的模板表格</Button>
          </div>
          <div className={style['title-block']}>
            <div className={style['title-line']}>
              <span className={style['title-text']}>2. 上传完善后的案件表格</span>
              <a className={style['a-btn']} onClick={() => setVisible(true)}>导入历史</a>
            </div>
          </div>
          <div className={style['input-block']} id='uploadBlock' draggable={true}>
            <div className={style['input-icon-line']}>
              <img src={file === null ? unPic : onPic} />
            </div>
            {
              file !== null && (
                <>
                  <div className={style['input-text-line']}>
                    {file.name}
                  </div>
                  <div className={style['input-btn-line']}>
                    <Space size={12}>
                      <span className={style.btn} onClick={() => setFile(null)}>取消导入</span>
                      <label>
                        <input type='file' className={style.file} accept='.xls,.xlsx' onChange={e => changeFile(e.target.files, setFile)} />
                        <span className={style.btn}>重新选择</span>
                      </label>
                    </Space>
                  </div>
                </>
              )
            }
            {file === null && (
              <>
                <div className={style['input-select-btn-line']}>
                  <label>
                    <input type='file' className={style.file} accept='.xlsx' onChange={e => changeFile(e.target.files, setFile)} />
                    <span className={style.btn}>选择文件</span>
                  </label>
                </div>
                <div className={style['input-text-line']}>
                  下载模板并完善信息后，可直接将文件拖拽到此处进行上传，支持格式：XLSX
                </div>
              </>
            )}
          </div>
          <div className={style['sub-line']}>
            <Space size={12}>
              <Button type='primary' disabled={file === null} onClick={() => confirmImport(file, setFile, dispatch)}>导入</Button>
            </Space>
          </div>
        </div>
      </div>
    </div>
  )
}

export default Main
